import React, { useRef } from 'react'
import { useState } from 'react'
import { Items } from './compnents/Items/Items'
import './App.css'
import Form from './compnents/Form/Form'
import { SexFilter } from './compnents/Items/SexFilter/SexFilter'
export const App = () => {
    let [counter, setCounter] = useState(1);
    const counterPlusAction = () => {
        setCounter( (val) => {
            console.log(val)
            return val + 1
        })
    }
    const counterDOMAction = () => {
        let p = counterRef.current
        console.log(p.innerText)
    }
    
    const counterRef = useRef()


    const [data, setData] = useState([
        { name: '第一位', age: 18, sex: '男', id: '001'},
        { name: '第二位', age: 18, sex: '女', id: '002' },
        { name: '第三位', age: 4, sex: '女', id: '003' }
    ]) 

    const [filterData, setFilterData] = useState([...data])

    const addPersonHandle = (info) => {
        info.id = '000'+data.length
        setData([info, ...data])
    }

    const deleteInfoHandle = (index) => {
        let newData = [...data]
        newData.splice(index, 1)
        setData(newData)
    }

    const sexChanged = (value) => {
        setSexFilter(value)
        if (value === '全部') {
            setFilterData(data)
        } else {
            setFilterData(data.filter((item) => item.sex === value))
        }
    }
    
    // 这里使用index来当key，如果当列表发生变化是有影响的，key需要用每一项的唯一ID
    const dataItem =  filterData.map((item, index) => {
        return <Items info={item} key={item.id} dataIndex={index} deleteInfo={deleteInfoHandle}></Items>
    })

    const [sexFilter, setSexFilter] = useState("全部");
    
    return (
        <div className='container'>
            <div className='counter'>
                <p style={{color: '#ff4700'}} ref={counterRef}>{counter}</p>
                <button onClick={counterPlusAction}>+</button>
                <button onClick={counterDOMAction}>获取dom对象</button>
            </div>
            
            <Form addPerson={addPersonHandle}></Form>
            <SexFilter onChanged={sexChanged} value={sexFilter}></SexFilter>
            {dataItem.length ? dataItem : '无数据'}
        </div>
    )

}
